<!--
 * @Descripttion: (销售明细报表/V_SaleOrderDetail)
 * @Author: (admin)
 * @Date: (2025-07-31)
-->

<template>
  <div>
       <AIResponseDialog ref="aiDialog" />
    <el-collapse>
      <el-collapse-item title="操作提示" name="1">
        <div>*1、全部  2、未结案 3、已结案   4、未结案成品。</div>
        <!-- <div>*待付款订单取消后则为已关闭。待付款订单支付后则为待发货。待发货订单发货后则为待收货。待收货订单收货后则为已完成。</div> -->
      </el-collapse-item>
    </el-collapse>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-tabs v-model="queryParams.orderStatus" class="demo-tabs" @tab-change="handleQuery">
        <el-tab-pane label="全部" name=""></el-tab-pane>
        <el-tab-pane :label="item.dictLabel" :name="parseInt(item.dictValue)" v-for="item in dictStore.orderDetailStatusOptions"></el-tab-pane>
      </el-tabs>
      <el-form-item label="客户名称" prop="cname">
        <el-input v-model="queryParams.cname" placeholder="请输入客户名称" />
      </el-form-item>
   <el-form-item label="是否成品" prop="PRODCLASSNAME">
            <el-select v-model="queryParams.PRODCLASSNAME" placeholder="是否成品" clearable style="width: 140px">
              <el-option label="全部"  value="" />
              <el-option v-for="dict in options.statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
      <el-form-item label="规格" prop="SPEC">
        <el-input v-model="queryParams.SPEC" placeholder="请输入规格" />
      </el-form-item>
    <el-form-item label="产品代码" prop="prod">
        <el-input v-model="queryParams.prod" placeholder="请输入产品代码" />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRangeCreateTime"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-time="defaultTime"
          :shortcuts="dateOptions">
        </el-date-picker>
      </el-form-item>  
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['oms:order:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange">
      <el-table-column label="AI" width="50">
        <template #default="scope">
          <el-button type="primary" size="small" title="AI详情" @click="handlePreview(scope.row)">
             <svg-icon name="ai" color="#fff" size="16"></svg-icon>
          </el-button>
          <!-- <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['gbsalesorder:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['gbsalesorder:delete']" @click="handleDelete(scope.row)"></el-button> -->
        </template>
      </el-table-column>
      <el-table-column prop="eri" label="订单Id" align="center" sortable v-if="columns.showColumn('eri')" /> 
      <el-table-column prop="sdate" label="订单时间" align="center"  width="120" :show-overflow-tooltip="true" sortable v-if="columns.showColumn('sdate')" /> 
       <el-table-column prop="code" label="订单号" align="center"  width="120"  sortable v-if="columns.showColumn('code')" /> 
      <el-table-column prop="cname" label="客户名称" align="center" :show-overflow-tooltip="true" width="150" sortable v-if="columns.showColumn('cname')" /> 
      <!-- <el-table-column prop="prod" label="产品代码" align="center" sortable v-if="columns.showColumn('prod')" />   -->
      <el-table-column label="产品代码" align="center" aria-setsize="10" prop="prod" width="100">
        <template #default="scope">
          <el-link type="primary" @click="handleProd(scope.row)">{{ scope.row.prod }}</el-link>
        </template>
      </el-table-column>
        
      
       <el-table-column prop="prodName" label="品名"   width="150" v-if="columns.showColumn('prodName')" />
      <el-table-column prop="spec" label="规格"  width="150"  v-if="columns.showColumn('spec')" />
  <el-table-column prop="qty" label="订单数" align="right" width="100":show-overflow-tooltip="true" v-if="columns.showColumn('qty')" />
    <el-table-column prop="noOutQty" label="未完数"  align="right" width="100":show-overflow-tooltip="true" v-if="columns.showColumn('noOutQty')" />
       
   
      <el-table-column label="库存数" align="center" aria-setsize="10" prop="cqty" width="100">
        <template #default="scope">
          <el-link type="primary" @click="handleQTY(scope.row)">{{ scope.row.cqty }}</el-link>
        </template>
      </el-table-column>
 <!-- <el-table-column prop="dlvdate" label="到达日期"  :show-overflow-tooltip="true" v-if="columns.showColumn('dlvdate')" /> -->
<el-table-column 
  prop="dlvdate"   label="出货时间"    :show-overflow-tooltip="true"   width="120" v-if="columns.showColumn('dlvdate')"  :formatter="formatDate"
/>
 <el-table-column prop="memO1" label="具体更改事宜" width="200" :show-overflow-tooltip="true" v-if="columns.showColumn('memO1')" />
 <el-table-column prop="prodclassname" label="类型" :show-overflow-tooltip="true" v-if="columns.showColumn('prodclassname')" />
     
       <el-table-column prop="closetype" label="状态" :show-overflow-tooltip="true" v-if="columns.showColumn('closetype')" />
 </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单备注" prop="orderNote">
              <el-input v-model="form.orderNote" placeholder="请输入订单备注" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="商家备注" prop="merchantNote">
              <el-input v-model="form.merchantNote" placeholder="请输入商家备注" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="确认收货状态" prop="confirmStatus">
              <el-radio-group v-model="form.confirmStatus">
                <el-radio v-for="item in options.confirmStatusOptions" :key="item.dictValue" :value="parseInt(item.dictValue)">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="物流公司" prop="deliveryCompany">
              <el-input v-model="form.deliveryCompany" placeholder="请输入物流公司" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="物流单号" prop="deliveryNo">
              <el-input v-model="form.deliveryNo" placeholder="请输入物流单号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="saleorderdetail">
import { listSaleOrderDetail, getSaleOrderDetail } from '@/api/buss/saleorderdetail.js'
  import { API_QueryAI } from '@/api/common.js' 
import { dayjs, ElMessage } from 'element-plus'
import router from '@/router'
import useDictStore from '@/store/modules/dict'
import AIResponseDialog from '@/components/AIResponseDialog/index.vue'
const aiDialog = ref()
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'ERI',
  sortType: 'asc',
  cname: undefined, 
  tenantId: 1, 
  SPEC: undefined, 
  PRODCLASSNAME: undefined, 
  prodName: undefined, 
  code: undefined, 
  prod: undefined, 
  SDATE: undefined  
})

// 设置默认日期范围为当前月第一天和最后一天
const setDefaultDateRange = () => {
  const now = new Date()
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  dateRangeCreateTime.value = [
    firstDay.toISOString().replace('T', ' ').substring(0, 10),
    lastDay.toISOString().replace('T', ' ').substring(0, 10)
  ]
}

onMounted(() => {
  setDefaultDateRange()
})
const dictStore = useDictStore()
const columns = ref([
  { visible: false, align: 'center', type: '', prop: 'eri', label: '订单Id' },
  { visible: true, align: 'center', type: '', prop: 'cname', label: '客户名称', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'code', label: 'CODE' },
  { visible: true, align: 'center', type: '', prop: 'prod', label: '产品代码' },
    // <el-table-column label="机器号" align="center" prop="prod" width="90">
    //     <template #default="scope">
    //       <el-link type="primary" @click="handleProd(scope.row)">{{ scope.row.prod }}</el-link>
    //     </template>
    //   </el-table-column>
  { visible: true, align: 'center', type: '', prop: 'prodName', label: '品名' },
  { visible: true, align: 'center', type: '', prop: 'spec', label: '规格' }, 
  { visible: true, align: 'center', type: '', prop: 'qty', label: '数量' }, 
  { visible: true, align: 'center', type: '', prop: 'nooutqty', label: '未出货数' },  
  { visible: true, align: 'center', type: 'dict', prop: 'closetype', label: '是否结案' },
    // { visible: true, align: 'center', type: 'dict', prop: 'orderStatus', label: '订单状态' },
  { visible: true, align: 'center', type: '', prop: 'date', label: '下单时间', showOverflowTooltip: true },
  { visible: false, align: 'center', type: '', prop: 'dlvdate', label: '到达日期', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'memO1', label: '订单备注', showOverflowTooltip: true }, 
  { visible: true, align: 'center', type: '', prop: 'prodclassname', label: '是否成品', showOverflowTooltip: true }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1), new Date(2000, 2, 1)])
const end = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD')  
const start = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
// 下单时间时间范围
const dateRangeCreateTime = ref([])

var dictParams = []

function getList() {
  proxy.addDateRange(queryParams, dateRangeCreateTime.value, 'SDATE')
  loading.value = true
  listSaleOrderDetail(queryParams).then((res) => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  // if (queryParams.orderStatus == '') {
  //   dateRangeCreateTime.value = [start, end]
  // }
  getList()
}

// 重置查询操作
function resetQuery() {
  // 下单时间时间范围
  dateRangeCreateTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order
  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    ERI: [{ required: true, message: '订单不能为空', trigger: 'blur', type: 'string' }]
  },
  options: {
    confirmStatusOptions: [
      { dictLabel: '未结案', dictValue: '0' },
      { dictLabel: '已结案', dictValue: '1', listClass: 'success' },
      { dictLabel: '未结案成品', dictValue: '2', listClass: 'danger' }
    ],
    statusOptions: [
      { dictLabel: '成品', dictValue: '成品', listClass: 'success'  },
      { dictLabel: '配件', dictValue: '配件', listClass: 'danger'  }
    ]
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    ERI: null,
    SDATE: null,
    CNAME: null,
    CODE: null,
    PROD: null,
    ProdName: null,
    SPEC: null,
    QTY: null,
    DLVDATE: null,
    MEMO1: null,
    PRODCLASSNAME: null,
    CLOSETYPE: null,
    NoOutQty: null 
  }
  proxy.resetForm('formRef')
}
/**
 * 查看
 * @param {*} row
 */
function handlePreview(row) {
  var data = {
    title: 'SaleOrderDetail',
    Prompt: row.eri,
  };
 API_QueryAI(data).then((res) => {
    const data = JSON.stringify(res.data.table1[0] || '无') ;
     const prom = JSON.stringify(res.data.table2[0].prompt||'无') ;
   //console.log(data)

    aiDialog.value?.openDialog()
  aiDialog.value?.clearMessages();
  // 准备提示词
  const prompt =  data +prom
// 请从以下几个方面进行分析：
// 1. 库存水平评估
// 2. 可能的补货建议
// 3. 潜在问题分析
// 4. 优化建议
  // 添加用户消息
  aiDialog.value?.addMessage({
    role: 'user',
    content:  prompt  
  })

  // 添加空的AI消息用于流式响应
  aiDialog.value?.addMessage({
    role: 'assistant',
    content: '',
    isStreaming: true
  })

  // 调用DeepSeek API
  aiDialog.value?.queryAI(prompt)
  })
  
}

 
function handleProd(row) {
  const prod = row.prod; 
  // var hasPermi = proxy.$auth.hasPermiAnd(['system:role:authorize', 'system:roleusers:list'])
  // if (hasPermi) {
    router.push({ path: '/sale/SaleVBOMWORK', query: { prod } })
  // } else {
  //   proxy.$modal.msgError('你没有权限访问')
  // }
}

function handleQTY(row) {
  const prod = row.prod; 
  // var hasPermi = proxy.$auth.hasPermiAnd(['system:role:authorize', 'system:roleusers:list'])
  // if (hasPermi) {
    router.push({ path: '/sale/SaleVPROD', query: { prod } })
  // } else {
  //   proxy.$modal.msgError('你没有权限访问')
  // }
}
// 添加&修改 表单提交vv
// 删除按钮操作
 
// 导出按钮操作
function handleExport() {
  proxy
    .$confirm('是否确认导出订单管理数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      await proxy.downFile('/buss/SaleOrderDetail/export', { ...queryParams })
    })
}
function copySuccess() {
  ElMessage.success('复制成功')
}
 
 
/**
 * 详情
 * @param row
 */
function handleDetails(row) {
  router.push({
    path: '/sale/Sale_V_PROD',
    query: {
      id: row.RPOD
    }
  })
}
// handleQuery()
</script>
<style lang="scss" scoped>
.amount_label {
  width: 60px;
  display: inline-block;
}
.flex {
  display: flex;
}

.order-product {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  margin-top: 12px;
}

.order-product .info {
  flex: 1;
  padding: 0 10px;
}

.order-product .price {
  color: #f44;
}
</style>
 